

cc.Class({
    extends: require('UI-PanelWindow'),

    properties: {
        titles : [cc.Node],
        titleToggle : require('UI-ToggleGroup'),
        pageView : cc.PageView,
        mask :cc.Node,
        pageTime : {
            default : 0,
            tooltip:'翻页所需要的动画时间，0代表没有'
        },
        
        changePageEvents: {
            "default": [],
            type: cc.Component.EventHandler,
            tooltip: "i18n:COMPONENT.button.click_events"
        }
    },
    onLoad(){
        var handler = new cc.Component.EventHandler();
        handler.target = this.node;
        handler.component = 'PackageView';
        handler.handler = 'onClickTitle';
        this.titleToggle.clickEvents.push(handler)
    },
    start(){
        if(this.n_lastViewId == undefined){
            this.updateButton(-1,0)
        }
    },
    
    getPages(){
        return this.pageView.getPages();
    },
    getCurrentPageIndex(){
        return this.n_lastViewId;
    },
    onViewPage(){
        var viewId = this.pageView.getCurrentPageIndex()
        if(this.n_lastViewId == viewId){
            return;
        }
        cc.Component.EventHandler.emitEvents(this.changePageEvents, this,viewId);
        this.updateButton(this.n_lastViewId, viewId)
    },

    updateButton(last,viewId){
        this.n_lastViewId = viewId;
        var pages = this.pageView.getPages();
        if(viewId < pages.length){
            var last = pages[last];
            last&&last.js&&last.js.onPageHide && last.js.onPageHide();
            var page = pages[viewId];
            page&&page.js&&page.js.onPageShow && page.js.onPageShow();
        }
        this.titleToggle.setIndex(viewId);
    },

    setCurrentPage(viewId,time){
        if(this.n_lastViewId == viewId){
            return
        }
        cc.Component.EventHandler.emitEvents(this.changePageEvents, this,viewId);
        this.pageView.scrollToPage(viewId,time)
        this.updateButton(this.n_lastViewId,viewId);
    },

    onClickTitle(event){
        // cc.log('onClickTitle:',this.titleToggle.getIndex());
        this.setCurrentPage(this.titleToggle.getIndex(),this.pageTime)
    },
    // openViewMove 是否开启翻动翻页
    setOptions(options){
        options.openViewMove && (this.mask.active = !options.openViewMove);
        if(options.pageId != undefined){
            this.setCurrentPage(options.pageId,0.1)
            this.n_lastViewId = options.pageId
        }
        if(options.scrollEnable != null){
            options.scrollEnable ? this.pageView._registerEvent() : this.pageView._unregisterEvent();
        }
        options.pageId && this.titleToggle.setIndex(options.pageId);
    }

    // update (dt) {},
});
